package util

import (
	"crypto/md5"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"gmfs/core/logger"
	"io"
	"os"
	"path"
	"time"
)

/**
 * 检查文件是否存在
 */
func PathExist(filePath string) bool {
	_, err := os.Stat(filePath)
	if err != nil && os.IsNotExist(err) {
		return false
	}
	return true
}

/**
 * 获取文件后缀，例如 .exe
 */
func FileSuffix(fileName string) string {
	return path.Ext(path.Base(fileName))
}

/**
 * 判断上传文件是否为图片
 * buff, why 512 bytes ? see http://golang.org/pkg/net/http/#DetectContentType
 */
func IsImage(filetype string) bool {
	switch filetype {
	case "image/jpeg", "image/jpg", "image/gif", "image/png", "image/bmp":
		return true
	default:
		return false
	}
}

/**
 * 递归创建目录
 */
func Mkdir(filePath string) bool {
	err := os.MkdirAll(filePath, 0777)
	if err != nil {
		logger.Errorf("mkdir %s failed. %s", filePath, err)
		return false
	}
	return true
}

/**
 * File MD5
 */
func FileHashMD5(path string) (string, error) {
	file, err := os.Open(path)
	defer file.Close()
	if err != nil {
		return "", err
	}
	h := md5.New()
	io.Copy(h, file)
	return fmt.Sprintf("%x", h.Sum(nil)), nil
}

/**
 * Reader MD5
 */
func ReaderHashMD5(r io.Reader) (string, error) {
	if r == nil {
		return "", errors.New("ipt reader is nil")
	}
	h := md5.New()
	io.Copy(h, r)
	return fmt.Sprintf("%x", h.Sum(nil)), nil
}

/**
 * Byte MD5
 */
func ByteMD5(data []byte) string {
	h := md5.New()
	h.Write(data)
	return hex.EncodeToString(h.Sum(nil))
}

/**
 * 生成随机文件名, extension 文件扩展名
 * GenerateRandomFilename("jpg")
 */
func GenerateRandomFilename(dot bool, extension string) string {
	hash := sha256.New()
	hash.Write([]byte(fmt.Sprintf("%s", time.Now().Nanosecond())))
	md := hash.Sum(nil)
	mdStr := hex.EncodeToString(md)
	if dot {
		return fmt.Sprintf("%s.%s", mdStr, extension)
	} else {
		return fmt.Sprintf("%s%s", mdStr, extension)
	}
}
